package com.lzh.hosp.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzh.hosp.model.ResponseResult;
import com.lzh.hosp.model.SystemOperateLog;
import com.lzh.hosp.model.vo.OperateLogPageReqVO;
import com.lzh.hosp.service.SystemOperateLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Tag(name = "日志管理")
@RestController
@RequestMapping("/operateLog")
public class OperationLogController {
    @Autowired
    private SystemOperateLogService systemOperateLogService;

    @GetMapping("/page")
    @PreAuthorize("hasAuthority('sys:operationLog:query')")
    public ResponseResult pageOperateLog(@Valid OperateLogPageReqVO reqVO) {
        //构造分页条件
        Page<SystemOperateLog> page = new Page<>(reqVO.getPageNo(),reqVO.getPageSize());
        //构造查询条件
        QueryWrapper<SystemOperateLog> wrapper = new QueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(reqVO.getModule()),"module", reqVO.getModule());
        wrapper.eq(!StringUtils.isEmpty(reqVO.getType()),"type", reqVO.getType());
        if (!StringUtils.isEmpty(reqVO.getStartTime())){
            wrapper.ge(reqVO.getStartTime().length==2,"start_time", reqVO.getStartTime()[0]);
            wrapper.le(reqVO.getStartTime().length==2,"start_time", reqVO.getStartTime()[1]);
        }

        //构造success条件
        if (!StringUtils.isEmpty(reqVO.getSuccess())){
            if (reqVO.getSuccess()){
                //为真，查询结果为成功的日志
                wrapper.eq("result_code",200);
            }else{
                //为假，查询结果为失败的日志
                wrapper.ne("result_code",200);
            }
        }
        Page<SystemOperateLog> pageResult = systemOperateLogService.page(page, wrapper);
        return ResponseResult.ok(pageResult);
    }

    @GetMapping("/info/{id}")
    public ResponseResult info(@PathVariable Long id) {
        SystemOperateLog operateLog = systemOperateLogService.getById(id);
        return ResponseResult.ok(operateLog);
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response, @Valid OperateLogPageReqVO reqVO) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SystemOperateLog.class).sheet("模板").doWrite(getData(reqVO));
    }

    private List<SystemOperateLog> getData(OperateLogPageReqVO reqVO){
        //构造分页条件
        Page<SystemOperateLog> page = new Page<>(reqVO.getPageNo(),reqVO.getPageSize());
        //构造查询条件
        QueryWrapper<SystemOperateLog> wrapper = new QueryWrapper<>();
        wrapper.like(!StringUtils.isEmpty(reqVO.getModule()),"module", reqVO.getModule());
        wrapper.eq(!StringUtils.isEmpty(reqVO.getType()),"type", reqVO.getType());
        if (!StringUtils.isEmpty(reqVO.getStartTime())){
            wrapper.ge(reqVO.getStartTime().length==2,"start_time", reqVO.getStartTime()[0]);
            wrapper.le(reqVO.getStartTime().length==2,"start_time", reqVO.getStartTime()[1]);
        }

        //构造success条件
        if (!StringUtils.isEmpty(reqVO.getSuccess())){
            if (reqVO.getSuccess()){
                //为真，查询结果为成功的日志
                wrapper.eq("result_code",200);
            }else{
                //为假，查询结果为失败的日志
                wrapper.ne("result_code",200);
            }
        }
        Page<SystemOperateLog> pageResult = systemOperateLogService.page(page, wrapper);
        return pageResult.getRecords();
    }
}
